﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BrokerBase.Lib.Product;
using Broker.View.Comm;
using BrokerBase.Lib.Tool;

namespace Broker.View.ProductView
{
    /// <summary>
    /// AdjustRateItemForm.xaml 的交互逻辑
    /// </summary>
    public partial class AdjustRateItemForm
    {
        private IAdjustRateItem item;
        private IAdjustRateItem original;

        public AdjustRateItemForm(IAdjustRateItem item)
        {
            InitializeComponent();

            original = item;

            this.item = new AdjustRateItem(item.Owner);

            BaseTools.CopyTo<IAdjustRateItem>(original, this.item);

            Loaded += new RoutedEventHandler(AdjustRateItemForm_Loaded);

            PreviewClosed += new EventHandler<Telerik.Windows.Controls.WindowPreviewClosedEventArgs>(AdjustRateItemForm_PreviewClosed);

        }

        public bool IsCommit { get; set; }


        void AdjustRateItemForm_Loaded(object sender, RoutedEventArgs e)
        {
            DataContext = item;
        }

        void AdjustRateItemForm_PreviewClosed(object sender, Telerik.Windows.Controls.WindowPreviewClosedEventArgs e)
        {
            if (IsCommit)
            {
                if (Verify())
                    BaseTools.CopyTo<IAdjustRateItem>(item, original);
                else
                    e.Cancel = true;
            }
        }

        private void btnConfirm_Click(object sender, RoutedEventArgs e)
        {
            IsCommit = true;
            Close();
        }

        private bool Verify()
        {
            if (string.IsNullOrEmpty(item.Name))
            {
                MessageBox.Show("请输入名称!", "提示");
                return false;
            }

            int count=item.Owner.Items.Where(p=>p.Name==item.Name).Count();
            bool exists = item.Owner.Items.FirstOrDefault(p => p == item) == null;

            if (exists && count > 0)
            {
                MessageBox.Show("名称重复，请重新输入!", "提示");
                return false;
            }
            else if (!exists && count > 1)
            {
                MessageBox.Show("名称重复，请重新输入!", "提示");
                return false;
            }

            if (item.Value == 0)
            {
                MessageBox.Show("调整率不能等于零!", "提示");
                return false;
            }

            return true;
        }

        private void btnExit_Click(object sender, RoutedEventArgs e)
        {
            IsCommit = false;
            Close();
        }
    }
}
